
import 'package:fl_amap/fl_amap.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

import '../constant/app_info.dart';
import '../constant/keys.dart';
import '../page/rong_im/rong_base_logic.dart';
import '../util/logger_util.dart';
import '../widget/UpdateDialog.dart';

/// <summary>
/// author：zwb
/// dateTime： 2021/12/17 14:42
/// filePath： lib/init_sdk.dart
/// desc: 第三方SDK初始化
/// <summary>
///
class InitSdk {
  static String _platformVersion = 'Unknown';
  static GlobalKey<UpdateDialogState> _dialogKey = new GlobalKey();
  /// 初始化高地地图定位
  static gaoDelLocationInit() async {
    await setAMapKey(
      iosKey: Keys.gaoDeMapKeyIOS,
      androidKey: Keys.gaoDeMapKeyAndroid,
    ).then((value) {
        if(value) {
          print('高德地图ApiKey设置成功');
        }else{
          print('高德地图ApiKey设置失败');
        }
      },
    ).catchError(((error) {
        print("高德地图ApiKey设置出错 : ${error}");
      }),
    );
  }

  /// 初始化本地存储
  static spUtilInit() async{
    SpUtil.getInstance().then((value) {
      if(value != null){
        print("本地存储初始化成功");
      }else{
        print("本地存储初始化失败");
      }
    }).catchError((error) {
      print("本地存储初始化出错: $error");
    });
  }

  /// 初始化bug上报
  static buglyInit() async {
    await FlutterBugly.init(
      androidAppId: Keys.buglyKeyAndroid,
      iOSAppId: Keys.buglyKeyIos,
    ).then((value) {
      if(value!=null){
        _platformVersion = value.message;
        print("Bugly初始化成功");
      }else{
        print("Bugly初始化失败");
      }
    }).catchError((error) {
      print("Bugly初始化出错: $error");
    });
    // 当配置 customUpgrade=true 时候，这里可以接收自定义升级
    FlutterBugly.onCheckUpgrade.listen((_upgradeInfo) {
      print("Bugly onCheckUpgrade:${_upgradeInfo}");
      _showUpdateDialog(
        _upgradeInfo.newFeature,
        _upgradeInfo.apkUrl!,
        _upgradeInfo.upgradeType == 2,
      );
    });
    // FlutterBugly.setUserId("user id");
    // FlutterBugly.putUserData(key: "key", value: "value");
    int tag = 9527;
    FlutterBugly.setUserTag(tag);
  }

  static void _showUpdateDialog(String version, String url, bool isForceUpgrade) {
    Get.dialog(_buildDialog(version, url, isForceUpgrade));
  }

  static void checkUpgrade() async{
    print("获取更新中。。。");
    FlutterBugly.getUpgradeInfo().then((UpgradeInfo? info) {
      if (info != null && info.id != null) {
        print(info);
        // showUpdateDialog(info.newFeature, info.apkUrl);
      }
    });
  }

  static Widget _buildDialog(String version, String url, bool isForceUpgrade) {
    return WillPopScope(
      onWillPop: () async => isForceUpgrade,
      child: UpdateDialog(
        key: _dialogKey,
        version: version,
        onClickWhenDownload: (_msg) {
          // 提示不要重复下载
        },
        onClickWhenNotDownload: () {
          //下载 apk，完成后打开 apk 文件，建议使用 dio + open_file 插件
        },
      ),
    );
  }

  /// 融云
  static rongInit() async{
    await RongIMClient.init(Keys.rongAppKey);
    RongBaseLogic.listenerMessage();
    print("融云初始化成功");
  }

  /// 获取app信息
  static getAppInfo() async{
    if(kIsWeb) return; /// web端屏蔽 不支持
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    AppInfo.appName = packageInfo.appName;
    AppInfo.buildNumber = packageInfo.buildNumber;
    AppInfo.packageName = packageInfo.packageName;
    AppInfo.version = packageInfo.version;
    logger("${AppInfo()}",tag: "APP当前版本信息");
  }

  /// 微信初始化
  static weixinInit() async{
    registerWxApi(appId: Keys.wxAppKey,universalLink: "https://lnong.com.cn/").then((value){
      if(value){
        print("微信初始化成功");
      }
    }).catchError((onError){
      print("微信初始化出错：$onError");
    });
  }
}
